package com.crcode.crm.service.data.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.data.ProjectBean;
import com.crcode.crm.bean.log.DataLogBean;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.dao.accessory.AccessoryDao;
import com.crcode.crm.dao.data.ProjectDao;
import com.crcode.crm.dao.log.DataLogDao;
import com.crcode.crm.dao.progress.ProgressDao;
import com.crcode.crm.service.data.ProjectService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultUtil;

/**
 * 项目业务逻辑实现层
 * @author cl
 * @date 2019年3月25日
 */
@Service(value="projectService")
@Transactional
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private ProgressDao progressDao;
	@Autowired
	private AccessoryDao accessoryDao;
	@Autowired
	private DataLogDao dataLogDao;

	/**
	 * 根据序列化id查询
	 * @author: cl   
	 * @date: 2019年3月25日
	 * @param serializable
	 * @return
	 */
	@Override
	public ProjectBean getById(Integer serializable) {
		return projectDao.findById(serializable).orElse(null);
	}

	/**
	 * 保存返回实体
	 * @author: cl   
	 * @date: 2019年3月25日  
	 * @param t
	 * @return
	 */
	@Override
	public ProjectBean saveResultBean(ProjectBean t) {
		return projectDao.save(t);
	}

	/**
	 * 保存会返回true或false
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @param t
	 * @return
	 */
	@Override
	public boolean saveResultBoolean(ProjectBean t) {
		try {
			projectDao.save(t);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public ProjectBean updateResultBean(ProjectBean t) {
		return null;
	}

	@Override
	public boolean updateResultBoolean(ProjectBean t) {
		return false;
	}

	/**
	 * 根据序号删除
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @param serializable
	 * @return
	 */
	@Override
	public boolean delete(Integer serializable) {
		try {
			projectDao.deleteById(serializable);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 查询所有
	 * @author: cl   
	 * @date: 2019年3月25日 
	 * @return
	 */
	@Override
	public List<ProjectBean> getAll() {
		return projectDao.findAll();
	}

	/**
	 * 根据UUID查询
	 * @param uuid
	 * @return
	 */
	@Override
	public ProjectBean findByUuid(String uuid) {
		return projectDao.findByUuid(uuid);
	}

    /**
     * 根据主键批量物理删除
     * @author: cl   
     * @date: 2019年3月25日 
     * @param ids
     * @return
     */
	@Override
	public ResultUtil physicalDeleteByIds(String ids,UserBean user) {
		ResultUtil r = new ResultUtil();
		String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
		String [] arr = ids.split(",");
		long count=0;
		for (String str : arr) {
			Integer id=Integer.parseInt(str);
			ProjectBean p=projectDao.findById(id).orElse(null);
			if(p!=null){
				String dataUuid=p.getUuid();
				//删除方案
				accessoryDao.deleteByDataUuid(dataUuid);
				//删除进度
				progressDao.deleteByDataUuid(dataUuid);
				//删除文件
				MyFileUtil.deleteFile("project/"+dataUuid+"/plan");
				MyFileUtil.deleteFile("project/"+dataUuid+"/progress");
				//删除项目
				projectDao.deleteById(Integer.parseInt(str));
				count++;
				//保存日志
				DataLogBean l = new DataLogBean();
				l.setUserUuid(user.getUuid());
				l.setUserName(user.getUserRealName());
				l.setOperateTime(nowTime);
				l.setDataTuid(p.getUuid());
				l.setDataTitle(p.getProName());
				l.setLatestContent(null);
				l.setLogType(1);
				l.setOriginalContent(JSONObject.toJSONString(p));
				l.setOperateRemarks("该项目资源及其方案、进度等相关资料均以删除！");
				l.setDetailedType(3);
				dataLogDao.save(l);
			}
		}
		Boolean flag=true;
		if(count==0){
			flag=false;
		}
		r.setObj(null);
		r.setInfo(flag?"删除成功！":"删除失败！");
		r.setStatus(flag);
		return r;
	}
	
	/**
	 * 根据项目名称和企业UUID查询
	 * @param proName
	 * @param entUuid
	 * @return
	 */
	public ProjectBean findByProNameAndEntUuid(String proName,String entUuid){
		return projectDao.findByProNameAndEntUuid(proName,entUuid);
	}


	/**
	 * 根据查询条件查询
	 */
	@Override
	public Map<String, Object> findAll(Map<String, Object> params, PageVo vo) {
		int pageIndex = vo.getPageIndex() - 1;
		Pageable pageable = null;
		if(StringUtils.isNotEmpty(vo.getOrderBy())) {
			if(vo.getOrderDesc() == 1) {
				pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.DESC, vo.getOrderBy());
			}else if(vo.getOrderDesc() == 0) {
				pageable = PageRequest.of(pageIndex, vo.getPageSize(), Sort.Direction.ASC, vo.getOrderBy());
			}
		} else {
			pageable = PageRequest.of(pageIndex, vo.getPageSize());
		}
		Page<ProjectBean> page = projectDao.findAll(spec(params), pageable);
		Map<String, Object> rm = new HashMap<>();
		rm.put("total", page.getTotalElements());
		rm.put("tatalPages", page.getTotalPages());
		rm.put("rows", page.getContent());
		return rm;
	}

	/**
	 * 创建动态查询条件组合
	 * @param params 查询条件
	 * @return Specification<ProjectBean>
	 */
	private Specification<ProjectBean> spec(final Map<String, Object> params) {
		return new Specification<ProjectBean>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<ProjectBean> root, CriteriaQuery<?> criteriaQuery,
										 CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				//根据dataUUID查询
				if (params.get("entUuid") != null && params.get("entUuid") != "") {
					predicates.add(cb.equal(root.get("entUuid"), params.get("entUuid")));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
	}
	/**
     * 根据UUIDS设置可见权限
     * @author lxw
     * @date 2019年4月9日
     * @param uuids 资源UUIDS
	 * @param suuid 查看权限用户UUIDS
	 * @param sname查看权限用户名称集
	 * @param euuid编辑 权限用户UUIDS
	 * @param ename编辑权限用户名称集
	 * @param user 当前操作用户
     * @return
     */
    @Override
    public boolean empowerByIds(String uuids,String suuid,String sname,String euuid,String ename,UserBean user){
    	String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
		List<String> ul = Arrays.asList(uuids.split(","));
    	List<ProjectBean> le = this.projectDao.findByUuidIn(ul);
    	List<ProjectBean> pros = new ArrayList<>();
    	List<DataLogBean> logs = new ArrayList<>();
    	for (ProjectBean pro : le) {
    		ProjectBean p=pro;
    		pro.setSearchPowerUserUuids(suuid);
    		pro.setSearchPowerUserName(sname);
    		pro.setEditPowerUserUuids(euuid);
    		pro.setEditPowerUserName(ename);
			pros.add(pro);
			//保存日志
			DataLogBean l = new DataLogBean();
			l.setUserUuid(user.getUuid());
			l.setUserName(user.getUserRealName());
			l.setOperateTime(nowTime);
			l.setDataTuid(p.getUuid());
			l.setDataTitle(p.getProName());
			l.setLatestContent(JSONObject.toJSONString(pro));
			l.setLogType(1);
			l.setOriginalContent(JSONObject.toJSONString(p));
			l.setOperateRemarks("管理员分配该项目资源查看，编辑权限");
			l.setDetailedType(3);
			logs.add(l);
		}
    	boolean is = false;
    	try {
    		
    		projectDao.saveAll(pros);
    		dataLogDao.saveAll(logs);
    		is =true;
    		progressDao.updatePowerInfoByDataUuids(suuid, sname, euuid, ename, ul);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return is;
    }


	/**
	 * 根据用户/创建时间统计项目数量,按天统计
	 * @return List<Map<String, Object>>
	 */
	@Override
	public List<Map<String, Object>> aggsProByUserCreateTime(String uuid) {
		return this.projectDao.aggsProByUserCreateTime(uuid);
	}
	
	/**
	 * 设置项目的启动或者终止
	 * @author lxw
	 * @date 2019年4月19日
	 * @param isEnd 0、正常，1、终止
	 * @param uuids
	 * @return
	 */
	public ResultUtil setProjectStartOrEnd(UserBean user,Integer isEnd, String uuids){
		List<String> uuidl = Arrays.asList(uuids.split(",")); 
		ResultUtil r = new ResultUtil();
		this.progressDao.updateProStatsByDataUuids(isEnd, uuidl);
		long x = this.projectDao.updateProStatsByUuids(isEnd, uuidl);
		if(x>0){
			List<DataLogBean> logs = new ArrayList<>();
			String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
			List<ProjectBean> pl = this.projectDao.findByUuidIn(uuidl);
			for (ProjectBean pro : pl) {
				//保存日志
				DataLogBean l = new DataLogBean();
				l.setUserUuid(user.getUuid());
				l.setUserName(user.getUserRealName());
				l.setOperateTime(nowTime);
				l.setDataTuid(pro.getUuid());
				l.setDataTitle(pro.getProName());
				l.setLatestContent(JSONObject.toJSONString(pro));
				l.setLogType(1);
			
				pro.setProStats(isEnd);
				l.setOriginalContent(JSONObject.toJSONString(pro));
				l.setOperateRemarks(user.getUserRealName()+(isEnd==0?"-恢复了项目":"-终止了项目"));
				l.setDetailedType(3);
				logs.add(l);
			}
			this.dataLogDao.saveAll(logs);
		}
		r.setInfo(x>0?"操作成功":"操作失败");
		r.setStatus(x>0);
		return r;
	}

	/**
	 * 重置负责人
	 * @author lxw
	 * @date 2019年4月26日
	 * @param user 操作者
	 * @param uuids 资源UUIDS
	 * @param userUuid 用户序号
	 * @param userName 用户名称
	 * @return
	 */
	@Override
	public ResultUtil resetLiableUserByUuids(UserBean user, String uuids, String userUuid, String userName) {
		ResultUtil r = new ResultUtil();
		List<String> uuidl = Arrays.asList(uuids.split(",")); 
		List<ProjectBean> opl = this.projectDao.findByUuidIn(uuidl);
		long x  = this.projectDao.updateProLiableUserByUuids(userUuid, userName, uuidl);
		if(x>0){
			List<DataLogBean> logs = new ArrayList<>();
			String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
			for (ProjectBean pro : opl) {
				//保存日志
				DataLogBean l = new DataLogBean();
				l.setUserUuid(user.getUuid());
				l.setUserName(user.getUserRealName());
				l.setOperateTime(nowTime);
				l.setDataTuid(pro.getUuid());
				l.setDataTitle(pro.getProName());
				l.setLatestContent(JSONObject.toJSONString(pro));
				l.setLogType(1);
				pro.setLiableUserName(userName);
				pro.setLiableUserUuid(userUuid.trim());
				l.setOriginalContent(JSONObject.toJSONString(pro));
				l.setOperateRemarks(user.getUserRealName()+("：将项目负责人更改为["+userName+"]"));
				l.setDetailedType(3);
				logs.add(l);
			}
			this.dataLogDao.saveAll(logs);
		}
		r.setInfo(x>0?"操作成功":"操作失败");
		r.setStatus(x>0);
		return r;
	}
}
